package com.llf.payment;

import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;

import com.llf.util.Constants;
import com.llf.util.MD5;
import com.tencent.mm.sdk.modelpay.PayReq;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.WXAPIFactory;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;

import java.util.LinkedList;
import java.util.List;
import java.util.Random;

/**
 * 支付宝和微信支付的列子 1.支付宝：去支付宝官网，点击商家服务，点击产品大全，找到无线支付下面的移动支付
 * 2.微信：上微信开放平台申请账号（必须是企业账号），然后创建项目，开通支付
 *
 * @author 刘灵锋
 */
public class MainActivity extends Activity {
    // 是第三方app和微信通信的openapi接口
    private IWXAPI api;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
//		registerToWeixin();
    }

    private void registerToWeixin() {
        // 通过WXAPIFactory获得IWXAPI实例
        api = WXAPIFactory.createWXAPI(this, Constants.APP_ID, true);
        // 注册到微信
        api.registerApp(Constants.APP_ID);
    }

    // 支付宝支付
//    public void alipay(View v) {
//        AsyncTask<String, Void, String> task = new AsyncTask<String, Void, String>() {
//
//            @Override
//            protected String doInBackground(String... params) {
//                String payInfo = Alipay.pay();
//                // 构造PayTask对象
//                PayTask alipay = new PayTask(MainActivity.this);
//                // 调用支付接口，获取支付结果
//                String result = alipay.pay(payInfo);
//                return result;
//            }
//
//            @Override
//            protected void onPostExecute(String result) {
//                PayResult payResult = new PayResult(result);
//                String resultStatus = payResult.getResultStatus();
//                if (TextUtils.equals(resultStatus, "9000")) {
//                    Toast.makeText(MainActivity.this, "支付成功",
//                            Toast.LENGTH_SHORT).show();
//                } else {
//                    if (TextUtils.equals(resultStatus, "8000")) {
//                        Toast.makeText(MainActivity.this, "支付结果确认中",
//                                Toast.LENGTH_SHORT).show();
//                    } else {
//                        Toast.makeText(MainActivity.this, "支付失败",
//                                Toast.LENGTH_SHORT).show();
//                    }
//                }
//            }
//        };
//
//        task.execute();
//    }

    // 微信支付
    public void weixin(View v) {
        AsyncTask<String, Void, String> task = new AsyncTask<String, Void, String>() {

            @Override
            protected String doInBackground(String... params) {
                // 将订单提交到服务端生成预付单，返回prepay_id
                String prepay_id = "1101000000140415649af9fc314aa427";
                return prepay_id;
            }

            @Override
            protected void onPostExecute(String result) {
                PayReq request = new PayReq();
                request.appId = "wxd930ea5d5a258f4f";
                // 商户号
                request.partnerId = "1900000109";
                // 预支付交易会话ID
                request.prepayId = "1101000000140415649af9fc314aa427";
                // 扩展字段暂填写固定值Sign=WXPay
                request.packageValue = "Sign=WXPay";
                // 随机字符串
                request.nonceStr = genNonceStr();
                // 时间戳
                request.timeStamp = String.valueOf(genTimeStamp());

                List<NameValuePair> signParams = new LinkedList<NameValuePair>();
                signParams.add(new BasicNameValuePair("appid", request.appId));
                signParams.add(new BasicNameValuePair("noncestr",
                        request.nonceStr));
                signParams.add(new BasicNameValuePair("package",
                        request.packageValue));
                signParams.add(new BasicNameValuePair("partnerid",
                        request.partnerId));
                signParams.add(new BasicNameValuePair("prepayid",
                        request.prepayId));
                signParams.add(new BasicNameValuePair("timestamp",
                        request.timeStamp));
                // 签名
                request.sign = genAppSign(signParams);
                api.sendReq(request);
            }

        };
        task.execute();
    }

    private String genNonceStr() {
        Random random = new Random();
        return MD5.getMessageDigest(String.valueOf(random.nextInt(10000))
                .getBytes());
    }

    private long genTimeStamp() {
        return System.currentTimeMillis() / 1000;
    }

    private String genAppSign(List<NameValuePair> params) {
        StringBuilder sb = new StringBuilder();

        for (int i = 0; i < params.size(); i++) {
            sb.append(params.get(i).getName());
            sb.append('=');
            sb.append(params.get(i).getValue());
            sb.append('&');
        }
        sb.append("key=");
        sb.append("akakjs");// API_KE API秘钥，在商户平台申请

        sb.append("sign str\n" + sb.toString() + "\n\n");
        String appSign = MD5.getMessageDigest(sb.toString().getBytes())
                .toUpperCase();
        return appSign;
    }
}
